package cn.tedu.egweibo4.controller;

import cn.tedu.egweibo4.commen.response.JsonResult;
import cn.tedu.egweibo4.commen.response.StatusCode;
import cn.tedu.egweibo4.mapper.UserMapper;
import cn.tedu.egweibo4.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo4.pojo.dto.UserRegDTO;
import cn.tedu.egweibo4.pojo.entity.User;
import cn.tedu.egweibo4.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册功能
     */
    @ApiOperation(value = "用户注册")
    @PostMapping(value = "/reg")
    public JsonResult reg(@RequestBody UserRegDTO userRegDTO){
        //打桩
        log.debug(userRegDTO.toString());
        //校验用户名
        UserVO userVO = userMapper.selectUser(userRegDTO.getUsername());
        if (userVO != null)
            return new JsonResult(StatusCode.USERNAME_ALREADY_EXISTS);
        //注册
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insertUser(user);
        return JsonResult.success();
    }

    /**
     * 用户登录功能
     */
    @ApiOperation(value = "用户登录")
    @PostMapping(value = "/login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO,
                            @ApiIgnore HttpSession session){
        //打桩
        log.debug(userLoginDTO.toString());
        //校验用户名和密码
        UserVO userVO = userMapper.selectUser(userLoginDTO.getUsername());
        if (userVO==null)
            return new JsonResult(StatusCode.USERNAME_ERROR);
        if (!userVO.getPassword().equals(userLoginDTO.getPassword()))
            return new JsonResult(StatusCode.PASSWORD_ERROR);
        //登录
        session.setAttribute("user",userVO);
        return JsonResult.success();
    }

    /**
     * 获取当前用户功能
     */
    @ApiOperation(value = "获取当前用户")
    @GetMapping(value = "/currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        return JsonResult.success(userVO.getId()+"，"+userVO.getNickname());
    }

    /**
     * 用户退出功能
     */
    @ApiOperation(value = "用户退出")
    @GetMapping(value = "/logout")
    public JsonResult logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return JsonResult.success();
    }
}
